package com.lyn.mvp_demo.mvp.view.fragment;

import android.hardware.Camera;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.lyn.mvp_demo.databinding.FragmentCameraBinding;


public class CameraFragment extends BaseFragment<FragmentCameraBinding> implements SurfaceHolder.Callback, Camera.PreviewCallback {
    private Camera camera;
    private Camera.PreviewCallback previewCallback;

    public void setPreviewCallback(Camera.PreviewCallback previewCallback) {
        this.previewCallback = previewCallback;
    }

    @Override
    public FragmentCameraBinding getViewBinding(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return FragmentCameraBinding.inflate(inflater, container, false);
    }

    @Override
    public void create() {
        SurfaceHolder cameraSurfaceHolder = viewBinding.cameraSurface.getHolder();
        cameraSurfaceHolder.addCallback(this);
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        try {
            openCamera(0, surfaceHolder);
        } catch (Exception e) {
            e.printStackTrace();
            closeCamera();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        closeCamera();
    }

    private void openCamera(int cameraId, SurfaceHolder surfaceHolder) throws Exception {
        camera = Camera.open(cameraId);
        Camera.Parameters parameters = camera.getParameters();
        parameters.setPreviewSize(480, 640);
        camera.setParameters(parameters);
        camera.setPreviewDisplay(surfaceHolder);
        Camera.Size size = parameters.getPreviewSize();
        camera.addCallbackBuffer(new byte[size.width * size.height * 3 / 2]);
        camera.setPreviewCallbackWithBuffer(this);
        camera.startPreview();
    }


    @Override
    public void onPreviewFrame(byte[] bytes, Camera camera) {
        try {
            if (previewCallback != null) {
                previewCallback.onPreviewFrame(bytes, camera);
            }
        } finally {
            camera.addCallbackBuffer(bytes);
        }

    }

    private void closeCamera() {
        if (camera == null) return;
        camera.stopPreview();
        camera.release();
    }
}
